package com.yudaxian.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yudaxian.common.HoneyLogs;
import com.yudaxian.common.enums.LogType;
import com.yudaxian.common.vo.Result;
import com.yudaxian.sys.entity.Sensor;
import com.yudaxian.sys.service.ISensorService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yudaxian
 * @since 2023-12-01
 */
@RestController
@RequestMapping("/sensor")
public class SensorController {


    @Resource
    private ISensorService sensorService;

    @GetMapping("/all")
    public Result<List<Sensor>> getAllSensors() {
        List<Sensor> sensors = sensorService.list();
        return Result.success(sensors);
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getSensorList(
            @RequestParam(value = "sensorName", required = false) String sensorName,
            @RequestParam(value = "pageNo") Integer pageNo,
            @RequestParam(value = "pageSize") Integer pageSize) {

        LambdaQueryWrapper<Sensor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(sensorName), Sensor::getSensorName, sensorName);

        Page<Sensor> page = new Page<>(pageNo, pageSize);
        sensorService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @HoneyLogs(operation = "传感器", type = LogType.ADD)
    @PostMapping("/add")
    //RequestBody，json转Sensor对象，前端输入数据，传给后台json，再转成对象，存入数据库
    public Result<?> addSensor(@RequestBody Sensor sensor) {
        sensorService.addSensor(sensor);
        return Result.success("新增传感器成功");
    }

    @HoneyLogs(operation = "传感器", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result<?> updateSensor(@RequestBody Sensor sensor) {
        sensorService.updateSensor(sensor);
        return Result.success("修改成功");
    }

    @GetMapping("{id}")
    public Result<Sensor> getSensorById(@PathVariable("id") Integer id) {
        Sensor sensor = sensorService.getSensorById(id);

        return Result.success(sensor);
    }

    @HoneyLogs(operation = "传感器", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteSensorById(@PathVariable("id") Integer id) {
        sensorService.deleteSensorById(id);

        return Result.success("删除成功");
    }


}
